<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery@1.11.1/dist/jquery.min.js"></script>
    <style>
        .rightValidate {
            width: 350px;
            margin: 0px auto;
            position: relative;
            line-height: 33px;
            height: 33px;
            text-align: center;
            z-index: 99;
        }

        .v_rightBtn {
            position: absolute;
            left: 0;
            top: 0;
            height: 33px;
            width: 40px;
            background: #ddd;
            cursor: pointer;
        }
        .imgBtn{
            width:50px;
            height: 50px;
            position: absolute;
            left: 0;
            display: none;
        }
        .imgBtn img{
            opacity: 0;
            filter: none;
        }
        .imgBg{
            position: relative;
            width: 350px;
            height: 0;
            box-shadow: 0px 4px 8px #3C5476;
        }

        .hkinnerWrap{
            border: 1px solid #eee;
        }
        .green{
            border-color:#34C6C2 !important;
        }
        .green .v_rightBtn{
            background: #34C6C2;
            color: #fff;
        }
        .red{
            border-color:red !important;
        }
        .red .v_rightBtn{
            background: red;
            color: #fff;
        }
        .refresh{
            position: absolute;
            width: 30px;
            height: 30px;
            right: 0;
            top: 0;
            font-size: 12px;
            color: #fff;
            text-shadow: 0px 0px 9px #333;
            cursor: pointer;
            display: none;
        }
        .notSel{
            user-select: none;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            -webkit-touch-callout: none;
        }
        #sent_sms_btn{
            background-color: #efefef
        }
    </style>
</head>
<body>
<h2>登录页面 login2</h2>
<h3>表单登录</h3>
<h5>如果短信验证码与图片验证码同时配置同一 uri 时，优先使用短信验证码，图片验证码失效</h5>
<h5>滑块验证码因与图片验证码对同一个链接进行验证, 滑块验证码优先级高于图片验证码, 图片验证码会失效: 在配置中注释滑块验证码 auth-urls: 可以使图片验证码生效; 注意验证码优先级.
</h5>
<!-- 通过 th:action 的方式支持 csrf 或者 添加隐藏域<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/> -->
<form id="reg-form" th:action="@{/authentication/form}" method="post">
    <table>
        <tr>
            <td>用户名：</td>
            <td><input type="text" name="username" value="admin" ><p style="color: #ff0000"
                                                                     id="error-name"></p></td>
        </tr>
        <tr>
            <td>密码：</td>
            <td><input type="password" name="password" value="admin"></td>
        </tr>
        <tr>
            <td>图形验证码：</td>
            <td>
                <input type="text" name="imageCode">
                <img class="img" th:src="@{/code/image}" style="width: 67px; height: 23px">
            </td>
        </tr>
        <tr>
            <td ><input type="checkbox" name="rememberMe" checked="true">记住我</input></td>
            <td><p style="color: #ff0000" id="error-code"></p></td>
        </tr>
        <tr>
            <td ><button id="btn-reg" type="button">登录ajax</button></td>
            <!-- 通过 form submit 不能接收错误信息, 通过 ajax 可接收错误信息 -->
            <td ><button type="submit">登录</button></td>
        </tr>
    </table>
</form>
<br>
<h3>滑块验证码</h3>
<h5>滑块验证码因与图片验证码对同一个链接进行验证, 滑块验证码优先级高于图片验证码, 图片验证码会失效: 在配置中注释滑块验证码 auth-urls: 可以使图片验证码生效; 注意验证码优先级.
</h5>
<!-- 通过 th:action 的方式支持 csrf 或者 添加隐藏域<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/> -->
<form id="sli-form" th:action="@{/authentication/form}" method="post">
    <table>
        <tr>
            <td>用户名：</td>
            <td><input type="text" name="username" value="admin" ><p style="color: #ff0000"
                                                                     id="error-name-sli"></p></td>
        </tr>
        <tr>
            <td>密码：</td>
            <td><input type="password" name="password" value="admin"></td>
        </tr>
        <tr>
            <td>滑块验证码：</td>
            <td>
                <input type="hidden" name="sliderToken">
                <div class="comImageValidate rightValidate">
                    <div class="hkinnerWrap" style="height: 33px;position: relative">
                        <span  class="v_rightBtn " th:data-uri="@{/slider/check}"><em class="notSel">→</em></span>
                        <span class="huakuai"  style="font-size: 12px;line-height: 33px;color: #A9A9A9;">向右滑动滑块填充拼图</span>
                        <input type = "hidden" name="sliderToken"/>
                    </div>
                    <span style="color: #ff0000" id="error-code-sli"></span>
                    <div class="imgBg">
                        <div class="imgBtn">
                            <img />
                        </div>
                        <span class="refresh" id="slider-refresh" th:data-uri="@{/code/slider}">刷新</span>
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <td ><button id="btn-reg-sli" type="button">登录ajax</button></td>
        </tr>
    </table>
</form>
<br>
<h3>手机登录</h3>
<form id="mobile-form" th:action="@{/authentication/mobile}" method="post">
    <table>
        <tr>
            <td>手机号码：</td>
            <td>
                <input type="tel" name="mobile" value="13345678980"><button type="button" id="sent_sms_btn">发送验证码</button>
                <p style="color: #ff0000" id="error-name-mobile"></p>
                <a th:href="@{/code/sms}" id="sms_uri" hidden="hidden" />
            </td>
        </tr>
        <tr>
            <td>手机验证码：</td>
            <td>
                <input type="text" name="smsCode">
            </td>
        </tr>
        <tr>
            <td ><input type="checkbox" name="rememberMe" checked="true">记住我</input></td>
            <td><p style="color: #ff0000" id="error-code-mobile"></p></td>
        </tr>
        <tr>
            <td ><button id="btn-mobile" type="button">登录ajax</button></td>
        </tr>
    </table>
</form>
<br>

<h3>社交登录</h3>
<a th:href="@{/auth/callback/qq}">QQ登录</a>
<a th:href="@{/auth/weixin}">微信登录</a>

<dev id="basePath" th:basePath="@{/}" style="display: none"/>
</body>
<script>
    var basePath = $("#basePath").attr("basePath");
    $.fn.serializeObject = function()
    {
        let o = {};
        let a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    }

    $(".img").click(function(){
        let uri = this.getAttribute("src");
        console.log(uri)
        let end = uri.indexOf('?', 0);
        console.log(end)
        if (end === -1) {
            uri = uri + '?'+ Math.random();
        } else {
            uri = uri.substring(0, end) + '?'+ Math.random();
        }
        console.log(uri)
        this.setAttribute('src', uri);
    });

    $("#sent_sms_btn").click(function () {
        let uri = $("#sms_uri").attr("href");
        console.log(document.getElementById("sent_sms_btn").parentElement.getElementsByTagName("input")[0]);
        let mobile =
            document.getElementById("sent_sms_btn").parentElement.getElementsByTagName("input")[0].value;
        console.log(mobile);
        uri = uri + "?mobile=" + mobile;
        console.log(uri);
        $.ajax({
            url: uri,
            type: "GET",
            dataType: "json",
            contentType: 'application/json; charset=UTF-8',
            success: function (data) {
                console.log("==========发生短信验证码成功============")
                // ...
                console.log(data)
                $("#error-name-mobile").text("")
                $("#error-code-mobile").text("")
                let expireIn = data.data
                $("#sent_sms_btn:button:not(:disabled)").attr("di", "di").attr("disabled", true).css("background-color", "#c2c2c2");
                let interval = setInterval(function () {
                    $("#sent_sms_btn").text("剩余 " + (expireIn--) + " 秒")
                    if (expireIn < 0) {
                        $("#sent_sms_btn").text("发送验证码")
                        $("#sent_sms_btn:button[di=di]").attr("disabled", false).removeAttr("di").css("background-color", "#efefef");
                        window.clearInterval(interval);
                    }
                }, 1000);

            },
            error: function (data) {
                console.log("==========发送短信验证码失败============")
                console.log(data)
                $("#error-name-mobile").text("")
                $("#error-code-mobile").text("")
                data = data.responseJSON
                if (undefined !== data) {
                    console.log(data);
                    // 错误代码看ErrorCodeEnum
                    if (data.code >= 900 && data.code < 1000) {
                        $("#error-name-mobile").text(data.msg)
                    } else if (data.code >= 600 && data.code < 700) {
                        $("#error-code-mobile").text(data.msg)
                    }
                }
            }
        })

    });


    function submitFormByAjax(url, formId, errorNameId, errorCodeId, imgId, refresh) {
        return function () {
            console.log(JSON.stringify($(formId).serializeObject()))
            $.ajax({
                // 如果用的是模板，则 url 可以使用注入的方式，会跟着配置动态改变
                url: url,
                data: JSON.stringify($(formId).serializeObject()),
                type: "POST",
                dataType: "json",
                contentType: 'application/json; charset=UTF-8',
                success: function (data) {
                    $(errorNameId).text("")
                    $(errorCodeId).text("")
                    console.log("==========注册成功============")
                    // 注册成功
                    // ...
                    console.log(data)
                    let uri = data.data.url
                    if (uri === null) {
                        uri = basePath
                    }
                    window.location.href = uri;
                },
                error: function (data) {
                    // 注册失败
                    $(errorNameId).text("")
                    $(errorCodeId).text("")
                    console.log("********注册失败*********")
                    console.log(data)
                    data = data.responseJSON
                    if (undefined !== data) {
                        console.log(data);
                        // 错误代码看ErrorCodeEnum
                        if (data.code >= 900 && data.code < 1000) {
                            $(errorNameId).text(data.msg)
                        } else if (data.code >= 600 && data.code < 700) {
                            $(errorCodeId).text(data.msg)
                        }
                    }
                    if (refresh) {
                        $(imgId).trigger("click");
                    }
                }
            })
            return
        };
    }


    $("#btn-mobile").click(
        submitFormByAjax($("#mobile-form").attr("action"), "#mobile-form", "#error-name-mobile", "#error-code-mobile", ".img-mobile", true)
    )


    $("#btn-reg").click(
        submitFormByAjax($("#reg-form").attr("action"), "#reg-form", "#error-name", "#error-code", ".img", true)
    )

    $("#btn-reg-sli").click(
        submitFormByAjax($("#sli-form").attr("action"), "#sli-form", "#error-name-sli", "#error-code-sli", ".img-sli", false)
    )


    // ===================== 滑块验证码 ========================

    var tokenId = "";
    var y = "";
    var x = "";
    $(".comImageValidate").ready(function () {
        let uri = $("#slider-refresh").attr("data-uri");
        console.log(uri);
        validateImageInit(uri);
        $(".refresh").click(function () {
            let uri = $(this).attr("data-uri");
            $(".imgBtn img").css('opacity', 0);
            validateImageInit(uri);
        })
        $(".hkinnerWrap").mouseover(function(){
            $(".imgBg").stop(false).animate({"height":"213px"},100,function () {
                $(".imgBtn").css("display","block");
                $(".refresh").css("display","block");
            });
        }).mouseleave(function () {
            $(".imgBg").stop(false).animate({"height":"0"},100,function () {
                $(".imgBtn").css("display","none");
                $(".refresh").css("display","none");
            });
        });
        $(".imgBg").mouseover(function () {
            $(".imgBg").stop(false).animate({"height":"213px"},100,function () {
                $(".imgBtn").css("display","block");
                $(".refresh").css("display","block");
            });
        }).mouseleave(function () {
            $(".imgBg").stop(false).animate({"height":"0"},100,function () {
                $(".imgBtn").css("display","none");
                $(".refresh").css("display","none");
            });
        })
        $('.v_rightBtn').on({
            mousedown: function(e) {
                $(".huakuai").html("");
                $(".hkinnerWrap").removeClass("red green")
                $(".imgBtn img").css("opacity", 1)
                var el = $(this);
                var os = el.offset();
                dx = e.pageX - os.left;
                //$(document)
                $(this).parents(".hkinnerWrap").off('mousemove');
                $(this).parents(".hkinnerWrap").on('mousemove', function(e) {
                    var newLeft=e.pageX - dx;
                    el.offset({
                        left: newLeft
                    });
                    var newL=parseInt($(".v_rightBtn").css("left"));
                    if(newL<=0){
                        newL=0;
                    }else if (newL>=298){
                        newL=306;
                    }
                    $(".v_rightBtn").css("left",newL+"px");
                    $(".imgBtn").offset({
                        left: newLeft
                    });
                    $(".imgBtn").css("left",newL+"px")
                }).on('mouseup', function(e) {
                    //$(document)
                    $(this).off('mousemove');
                })
            }
        }).on("mouseup",function () {
            $(this).parents(".hkinnerWrap").off('mousemove');
            var l=$(this).css("left");
            if(l.indexOf("px")!=-1){
                l=l.substring(0,l.length-2);
            }
            x = l;
            let uri = $(this).attr("data-uri");
            submitDate(l,y,tokenId, uri)
        })

    });
    /*图形验证*/
    function submitDate(x, y, tokenId, uri) {
        $.ajax({
            url:uri + "?x="+x+"&y="+y+"&sliderToken="+tokenId,
            dataType:'json',
            type: "POST",
            success:function (data) {
                if(data.code === 0){
                    console.log(data);
                    $(".hkinnerWrap").addClass("green").removeClass("red");
                    $(".hkinnerWrap input[name='sliderToken']").val(data.data);
                }
                else if (data.code === 606) {
                    console.log("不刷新, 用户重新操作: " + data);
                    $(".hkinnerWrap").addClass("red").removeClass("green");
                    $(".v_rightBtn").css("left", 0);
                    $(".imgBtn").css("left", 0);
                } else {
                    console.log("重新刷新: " + data);
                    $(".hkinnerWrap").addClass("red").removeClass("green");
                    $(".v_rightBtn").css("left", 0);
                    $(".imgBtn").css("left", 0);
                    let uri = $("#slider-refresh").attr("data-uri");
                    validateImageInit(uri);
                    // setTimeout(function(){
                    //     $(".hkinnerWrap").removeClass("red green");
                    //     $(".v_rightBtn").css("left",0);
                    //     $(".imgBtn").css("left",0);
                    // },500)
                    //validateImageInit();
                }
            }
        })
    }

    /*初始化图形验证码*/
    function validateImageInit(uri) {
        $.ajax({
            url:uri,
            dataType:'json',
            cache:false,
            type: "get",
            success:function (data) {
                console.log(data);
                $(".huakuai").html("向右滑动滑块填充拼图");
                $(".imgBg").css("background",'#fff url("data:image/jpg;base64,'+data.sourceImage+'")');
                $(".imgBtn").css('top',data.locationY+'px');
                $(".imgBtn").find("img").attr("src","data:image/png;base64,"+data.newImage)
                tokenId=data.token;
                y=data.locationY;
                $(".hkinnerWrap").removeClass("red green");
                $(".v_rightBtn").css("left",0);
                $(".imgBtn").css("left",0);
                $(".hkinnerWrap input[name='sliderToken']").val(tokenId);
            },error:function(err){
                console.log(err)
            }
        })
    }
    /**
     * 再次进行用户拖动行为验证
     * @returns {boolean}
     */
    function reValidateDeal(uri){
        var result = false;
        $.ajax({
            url: uri + "?x="+x+"&y="+y+"&sliderToken="+tokenId,
            dataType:'json',
            cache : false,
            async : false,
            type: "POST",
            success:function (data) {
                if(data==true){
                    result = true;
                }else {
                    result = false;
                }
            }
        })
        return result;
    }

</script>
</html>